import logging
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect
from app01 import models

# 配置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

PERMISSION_RELATIONS = {
    "user/list/": ["user/add/", "user/delete/", "user/edit/"],
    "role/list/": ["role/add/", "role/delete/", "role/edit/"],
    "label/list/": ["label/add/", "label/delete/", "label/edit/"],
}

class AuthMiddleware(MiddlewareMixin):
    """ 权限验证中间件 """

    def process_request(self, request):
        url_path = request.path_info
        logger.info(f"Requested URL: {url_path}")

        if url_path in ["/", "/login/", "/logout/", "/main/", "/favicon.ico"]:
            return None

        try:
            info_dict = request.session.get("info")
            user_id = info_dict.get("id")
            user_role = info_dict.get("role")
        except Exception as e:
            logger.error("Error retrieving session info: %s", e)
            return redirect("/login/")

        if user_role == "admin":
            logger.info("Admin user, access granted")
            return None
        else:
            try:
                user = models.User.objects.get(id=user_id)
                roles = user.role.all()
                labels = models.Label.objects.filter(role__in=roles)

                # 获取所有允许的URL，包含联集权限
                allowed_urls = set()
                for label in labels:
                    main_permission = label.url
                    allowed_urls.add(main_permission)
                    if main_permission in PERMISSION_RELATIONS:
                        allowed_urls.update(PERMISSION_RELATIONS[main_permission])

                logger.info(f"Allowed URLs: {list(allowed_urls)}")

                is_allowed = url_path in allowed_urls

                logger.info(f"Checking permissions for user {user.name} on {url_path}")
                logger.info(f"User roles: {[role.role_name for role in roles]}")
                logger.info(f"Allowed labels: {[label.url for label in labels]}")

                if not is_allowed:
                    logger.info(f"Access denied for user {user.name} on {url_path}")
                    return HttpResponse('您没有权限访问！')
                else:
                    logger.info(f"Access granted for user {user.name} on {url_path}")
            except Exception as e:
                logger.error("Error in permission check: %s", e)
                return HttpResponse('系统错误，请联系管理员。')
